import { useState } from "react";
import { List, ListItem } from "../components/ui-lib";

export type FormType = "input" | "select" | "number" | "checkbox" | "textarea";

export interface FormData {
  type: FormType;
  title: string;
  subTitle: string;
  id: string;
  value: string;
}

export const DynamicForm = (props: {
  formData: FormData[];
  update: (e: any) => void;
}) => {
  return (
    <List>
      {props.formData.map((e) => {
        return (
          <ListItem key={e.id} title={e.title} subTitle={e.subTitle}>
            {getFormItem(e.type)(e, props.update)}
          </ListItem>
        );
      })}
    </List>
  );
};

export const getFormItem = (type: FormType) => {
  const FormMap: Record<
    FormType,
    (e: FormData, update: (e: any) => void) => JSX.Element
  > = {
    input: (ele, update) => (
      <input
        type="text"
        defaultValue={""}
        onBlur={(e) => {
          update({
            type: ele.type,
            fieldName: ele.title,
            value: e.currentTarget.value,
          });
        }}
      ></input>
    ),
    number: () => <>2</>,
    select: () => <>3</>,
    checkbox: () => <>4</>,
    textarea: () => <>5</>,
  };
  return FormMap[type];
};
